package com.luoxiang.socialandroid.activity;

import static com.luoxiang.lib_common.common.Constants.MmkvConst.EXTRA;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.KEY;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.TOKEN;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSStsTokenCredentialProvider;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.google.gson.Gson;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;
import com.luoxiang.socialandroid.R;
import com.luoxiang.socialandroid.adapter.Selectorphoto2Adapter;
import com.luoxiang.socialandroid.adapter.SelectorphotoAdapter;
import com.luoxiang.socialandroid.base.BaseActivity;
import com.luoxiang.socialandroid.bean.MessageBean;
import com.luoxiang.socialandroid.bean.NumberBean;
import com.luoxiang.socialandroid.bean.TokenBean;
import com.luoxiang.socialandroid.utils.AESUtil;
import com.luoxiang.socialandroid.utils.CustomClickListener;
import com.luoxiang.socialandroid.utils.GlideEngine;
import com.luoxiang.socialandroid.utils.MmkvUtil;
import com.luoxiang.socialandroid.utils.NetUtils;
import com.luoxiang.socialandroid.utils.NetUtils2;
import com.yalantis.ucrop.UCrop;
import com.yalantis.ucrop.UCropImageEngine;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

public class ReportActivity extends BaseActivity {
    private EditText edt_fankui;
    private TextView tv_size;
    private int userId, dynamicId;
    private Button btn_commit, img_sendimage;
    private ImageView icon_back;
    private Selectorphoto2Adapter adapter;
    private ArrayList<LocalMedia> list;
    private RecyclerView rv_liebiaopic;
    private TextView tv_send_zheng;
    private ArrayList<String> listaliyun;
    private String paths, picturePath;
    private ArrayList<String> arrayList = new ArrayList();
    String aliyunnum;

    @Override
    protected void initListener() {
        icon_back.setOnClickListener(v -> finish());
        edt_fankui.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                tv_size.setText(String.valueOf(edt_fankui.getText().length()));
                if (edt_fankui.getText().length() == 0) {
                    tv_size.setTextColor(Color.parseColor("#999999"));
                } else {
                    tv_size.setTextColor(Color.parseColor("#835DFF"));
                }
            }
        });
        btn_commit.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                listaliyun = new ArrayList();
                if (edt_fankui.getText() != null) {
                    getToken(list, 0);

                } else {
                    ToastUtils.showShort(R.string.mi_qingtianxiemiaoshuneirongzaishi);
                }
            }

            @Override
            protected void onFastClick() {

            }
        });
        img_sendimage.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                sengjubao();
            }

            @Override
            protected void onFastClick() {
                ToastUtils.showShort(R.string.mi_dianjiguokuai);
            }
        });
    }

    @Override
    protected void initLayout(Bundle savedInstanceState) {
        setContentView(R.layout.activity_report);
        setStatusBarTranslucent();

    }

    @Override
    protected void initView() {
        list = new ArrayList<>();
        rv_liebiaopic = findViewById(R.id.rv_liebiaopic);
        edt_fankui = findViewById(R.id.edt_fankui);
        tv_size = findViewById(R.id.tv_size);
        tv_send_zheng = findViewById(R.id.tv_send_zheng);
        btn_commit = findViewById(R.id.btn_commit);
        icon_back = findViewById(R.id.icon_back);
        img_sendimage = findViewById(R.id.img_sendimage);
        adapter = new Selectorphoto2Adapter();
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(ReportActivity.this, LinearLayoutManager.HORIZONTAL, false);
        rv_liebiaopic.setLayoutManager(linearLayoutManager);
        rv_liebiaopic.setAdapter(adapter);
        Intent intent = getIntent();
        userId = intent.getIntExtra("userId", -1);
        dynamicId = intent.getIntExtra("dynamicId", -1);
        adapter.setOnAddClickListener(new Selectorphoto2Adapter.OnAddClickListener() {
            @Override
            public void onItemClicks(int position, int size) {
                tv_send_zheng.setText(getString(R.string.mi_shangchuanpingzheng) + "(" + size + "/5)");
            }
        });
    }

    /**
     * 举报
     */
    private void getcomplaint(String token, String extra, int toUserId, String content, String images, int dynamicId) {
        NetUtils.getInstance().getApiService().getcomplaint(token, extra, toUserId, content, images, dynamicId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        String data = numberBean.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        LogUtils.i("decryptStr43", decryptStr);
                        Gson gson = new Gson();
                        MessageBean bean = gson.fromJson(decryptStr, MessageBean.class);
                        int code = bean.getCode();
                        if (bean.getCode() == 0) {
                            ToastUtils.showShort(R.string.mi_ganxienindejubao);
                            finish();

                        } else {
                            ToastUtils.showShort(bean.getMsg());
                        }

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    private void sengjubao() {
        PictureSelector.create(ReportActivity.this)
                .openGallery(SelectMimeType.ofImage())
                .setImageEngine(GlideEngine.createGlideEngine())
                .setMaxSelectNum(5)
                .setCropEngine((fragment, srcUri, destinationUri, dataSource, requestCode) -> {
                    // 注意* 如果你实现自己的裁剪库，需要在Activity的.setResult();
                    // Intent中需要给MediaStore.EXTRA_OUTPUT，塞入裁剪后的路径；如果有额外数据也可以通过CustomIntentKey.EXTRA_CUSTOM_EXTRA_DATA字段存入；
                    UCrop uCrop = UCrop.of(srcUri, destinationUri, dataSource);
                    uCrop.setImageEngine(new UCropImageEngine() {
                        @Override
                        public void loadImage(Context context, String url, ImageView imageView) {
                            Glide.with(context).load(url).into(imageView);
                        }

                        @Override
                        public void loadImage(Context context, Uri url, int maxWidth, int maxHeight, OnCallbackListener<Bitmap> call) {
                            Glide.with(context).asBitmap().override(maxWidth, maxHeight).load(url).into(new CustomTarget<Bitmap>() {
                                @Override
                                public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                                    if (call != null) {
                                        call.onCall(resource);
                                    }
                                }

                                @Override
                                public void onLoadFailed(@Nullable Drawable errorDrawable) {
                                    if (call != null) {
                                        call.onCall(null);
                                    }
                                }

                                @Override
                                public void onLoadCleared(@Nullable Drawable placeholder) {
                                }
                            });
                        }
                    });
                    uCrop.start(fragment.requireActivity(), fragment, requestCode);
                })
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(ArrayList<LocalMedia> result) {
                        if (result.isEmpty()) {
                            return;
                        } else {
                            if (result != null) {
                                list.addAll(result);
                                img_sendimage.setVisibility(View.VISIBLE);
                            }
                            adapter.setData(list);
                            adapter.notifyDataSetChanged();
                            tv_send_zheng.setText(getString(R.string.mi_ganxienindejubao) + "(" + list.size() + "/5)");
                        }
                    }

                    @Override
                    public void onCancel() {

                    }
                });
    }

    public void getToken(List<LocalMedia> localMediaList, int index) {
        if (index >= localMediaList.size()) {
            //拿到图片上传后台
            Gson gson = new Gson();
            aliyunnum = gson.toJson(listaliyun);
            if (!edt_fankui.getText().toString().isEmpty()){
                getcomplaint(MmkvUtil.INSTANCE.decodeString(TOKEN), EXTRA, userId, edt_fankui.getText().toString(), aliyunnum, dynamicId);

            }else {
                ToastUtils.showShort(R.string.mi_qingshuruyaojubaodeneirong);
            }
        }
        if (localMediaList.size()>0){
             path = localMediaList.get(index).getCutPath();
            picturePath = getkey(path);
        }else {
            return;
        }


        getRequest();
        NetUtils2.getInstance().getApiService().getUploadToken()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        String data = numberBean.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        try {
                            LogUtils.i("decryptStrpp", decryptStr);
                            Gson gson = new Gson();
                            TokenBean tokenBean = gson.fromJson(decryptStr, TokenBean.class);
                            if (tokenBean != null) {
                                String endpoint = tokenBean.getData().getSts().getEndpoint();

                                // 在移动端建议使用STS的方式初始化OSSClient。
                                OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(tokenBean.getData().getSts().getAccessKeyId(), tokenBean.getData().getSts().getAccessKeySecret(), tokenBean.getData().getSts().getSecurityToken());
                                ClientConfiguration conf = new ClientConfiguration();
                                conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒。
                                conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒。
                                conf.setMaxConcurrentRequest(5); // 最大并发请求书，默认5个。
                                conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次。
                                OSS oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider, conf);
                                if (path!=null){
                                    Luban.with(ReportActivity.this)
                                            .load(path)
                                            .ignoreBy(500)
                                            .setCompressListener(new OnCompressListener() {
                                                @Override
                                                public void onStart() {
                                                }

                                                @Override
                                                public void onSuccess(File file) {
                                                    PutObjectRequest putObjectRequest = new PutObjectRequest(tokenBean.getData().getSts().getBucketName(), picturePath, file.getPath());
                                                    oss.asyncPutObject(putObjectRequest, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
                                                        @Override
                                                        public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                                                            listaliyun.add(picturePath);
                                                            getToken(localMediaList, index + 1);
                                                            LogUtils.d("aliossresult", "上传成功" + result.toString());

                                                        }

                                                        @Override
                                                        public void onFailure(PutObjectRequest request, ClientException clientException, ServiceException serviceException) {
                                                            LogUtils.d("aliossresult", "上传失败");
                                                        }
                                                    });
                                                }

                                                @Override
                                                public void onError(Throwable e) {
                                                    PutObjectRequest putObjectRequest = new PutObjectRequest(tokenBean.getData().getSts().getBucketName(), picturePath, path);
                                                    oss.asyncPutObject(putObjectRequest, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
                                                        @Override
                                                        public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                                                            listaliyun.add(picturePath);
                                                            getToken(localMediaList, index + 1);
                                                            LogUtils.d("aliossresult", "上传成功" + result.toString());

                                                        }

                                                        @Override
                                                        public void onFailure(PutObjectRequest request, ClientException clientException, ServiceException serviceException) {
                                                            LogUtils.d("aliossresult", "上传失败");
                                                        }
                                                    });
                                                }
                                            }).launch();
                                }

                            }
                        } catch (Exception e) {
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }


}